<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :inline="true" :model="queryParams" label-width="120px">
            <el-form-item label="描述" prop="description">
              <el-input v-model="queryParams.description" clearable placeholder="请输入描述" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="排序" prop="sort">
              <el-input v-model="queryParams.sort" clearable placeholder="请输入排序" @keyup.enter="handleQuery" />
            </el-form-item>
            <!--            <el-form-item label="是否删除：0-未删除，1-已删除" prop="isDeleted">-->
            <!--              <el-input v-model="queryParams.isDeleted" placeholder="请输入是否删除：0-未删除，1-已删除" clearable @keyup.enter="handleQuery" />-->
            <!--            </el-form-item>-->
            <el-form-item label="所属工作中心编码" label-width="160px" prop="workCenterCode">
              <el-input v-model="queryParams.workCenterCode" clearable placeholder="请输入所属工作中心编码" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="工位编码" prop="workstationCode">
              <el-input v-model="queryParams.workstationCode" clearable placeholder="请输入工位编码" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="工位名称" prop="workstationName">
              <el-input v-model="queryParams.workstationName" clearable placeholder="请输入工位名称" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="工位类型" prop="workstationType">
              <el-select v-model="queryParams.workstationType" clearable placeholder="请选择工位类型">
                <el-option :value="1" label="腻子间" />
                <el-option :value="2" label="木骨间" />
                <el-option :value="3" label="喷砂间" />
                <el-option :value="4" label="阻尼浆喷涂间" />
                <el-option :value="5" label="烘干间" />
                <el-option :value="6" label="底漆厚浆间" />
                <el-option :value="7" label="中涂喷涂间" />
                <el-option :value="8" label="面漆喷涂间" />
                <el-option :value="11" label="补焊间" />
                <el-option :value="12" label="交检台位" />
                <el-option :value="13" label="表面准备台位" />
                <el-option :value="15" label="进车线" />
                <el-option :value="16" label="出车线" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button icon="Search" type="primary" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['painting:workstation:add']" icon="Plus" plain type="primary" @click="handleAdd">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['painting:workstation:edit']" :disabled="single" icon="Edit" plain type="success" @click="handleUpdate()"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['painting:workstation:remove']" :disabled="multiple" icon="Delete" plain type="danger" @click="handleDelete()"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['painting:workstation:export']" icon="Download" plain type="warning" @click="handleExport">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="workstationList" @selection-change="handleSelectionChange">
        <el-table-column align="center" type="selection" width="55" />
        <el-table-column v-if="true" align="center" label="主键ID" prop="id" />
        <el-table-column align="center" label="状态" prop="status">
          <template #default="scope">
            <el-tag :type="STATUS_MAP[scope.row.status].type">
              {{ STATUS_MAP[scope.row.status].label }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" label="描述" prop="description" />
        <el-table-column align="center" label="排序" prop="sort" />
        <!--        <el-table-column label="是否删除：0-未删除，1-已删除" align="center" prop="isDeleted" />-->
        <el-table-column align="center" label="所属工作中心编码" prop="workCenterCode" />
        <el-table-column align="center" label="工位编码" prop="workstationCode" />
        <el-table-column align="center" label="工位名称" prop="workstationName" />
        <el-table-column align="center" label="工位类型" prop="workstationType">
          <template #default="scope">
            <el-tag v-if="scope.row.workstationType === 1" type="success">腻子间</el-tag>
            <el-tag v-else-if="scope.row.workstationType === 2" type="success">木骨间</el-tag>
            <el-tag v-else-if="scope.row.workstationType === 3" type="success">喷砂间</el-tag>
            <el-tag v-else-if="scope.row.workstationType === 4" type="success">阻尼浆喷涂间</el-tag>
            <el-tag v-else-if="scope.row.workstationType === 5" type="success">烘干间</el-tag>
            <el-tag v-else-if="scope.row.workstationType === 6" type="success">底漆厚浆间</el-tag>
            <el-tag v-else-if="scope.row.workstationType === 7" type="success">中涂喷涂间</el-tag>
            <el-tag v-else-if="scope.row.workstationType === 8" type="success">面漆喷涂间</el-tag>
            <el-tag v-else-if="scope.row.workstationType === 11" type="warning">补焊间</el-tag>
            <el-tag v-else-if="scope.row.workstationType === 12" type="warning">交检台位</el-tag>
            <el-tag v-else-if="scope.row.workstationType === 13" type="warning">表面准备台位</el-tag>
            <el-tag v-else-if="scope.row.workstationType === 15" type="warning">进车线</el-tag>
            <el-tag v-else-if="scope.row.workstationType === 16" type="warning">出车线</el-tag>
            <el-tag v-else type="danger">未知类型</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" class-name="small-padding fixed-width" fixed="right" label="操作" min-width="130">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button v-hasPermi="['painting:workstation:edit']" icon="Edit" link type="primary" @click="handleUpdate(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip :content="STATUS_MAP[scope.row.status === STATUS.ENABLED ? STATUS.DISABLED : STATUS.ENABLED].label" placement="top">
              <el-button
                v-hasPermi="['painting:workstation:edit']"
                :icon="scope.row.status === STATUS.ENABLED ? 'CircleClose' : 'CircleCheck'"
                :type="scope.row.status === STATUS.ENABLED ? 'danger' : 'success'"
                link
                @click="handleStatusChange(scope.row)"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button v-hasPermi="['painting:workstation:remove']" icon="Delete" link type="primary" @click="handleDelete(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="设置" placement="top">
              <el-button icon="Setting" link type="primary" @click="handleSetting(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="配置人员" placement="top">
              <el-button icon="Avatar" link type="primary" @click="handleStaffing(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNum" :total="total" @pagination="getList" />
    </el-card>
    <!-- 添加或修改工位管理对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" append-to-body width="800px">
      <el-form ref="workstationFormRef" :model="form" :rules="rules" label-width="140px">
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" placeholder="请输入内容" type="textarea" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="form.sort" placeholder="请输入排序" />
        </el-form-item>
        <!--        <el-form-item label="是否删除：0-未删除，1-已删除" prop="isDeleted">-->
        <!--          <el-input v-model="form.isDeleted" placeholder="请输入是否删除：0-未删除，1-已删除" />-->
        <!--        </el-form-item>-->
        <el-form-item label="所属工作中心编码" prop="workCenterCode">
          <el-input v-model="form.workCenterCode" placeholder="请输入所属工作中心编码" />
        </el-form-item>
        <el-form-item label="工位编码" prop="workstationCode">
          <el-input v-model="form.workstationCode" placeholder="请输入工位编码" />
        </el-form-item>
        <el-form-item label="工位名称" prop="workstationName">
          <el-input v-model="form.workstationName" placeholder="请输入工位名称" />
        </el-form-item>
        <el-form-item label="工位类型" prop="workstationType">
          <el-select v-model="form.workstationType" placeholder="请选择工位类型">
            <el-option :value="1" label="腻子间" />
            <el-option :value="2" label="木骨间" />
            <el-option :value="3" label="喷砂间" />
            <el-option :value="4" label="阻尼浆喷涂间" />
            <el-option :value="5" label="烘干间" />
            <el-option :value="6" label="底漆厚浆间" />
            <el-option :value="7" label="中涂喷涂间" />
            <el-option :value="8" label="面漆喷涂间" />
            <el-option :value="11" label="补焊间" />
            <el-option :value="12" label="交检台位" />
            <el-option :value="13" label="表面准备台位" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="STATUS.DISABLED">{{ STATUS_MAP[STATUS.DISABLED].label }}</el-radio>
            <el-radio :label="STATUS.ENABLED">{{ STATUS_MAP[STATUS.ENABLED].label }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 设置工位管理对话框 -->
    <el-dialog v-model="dialogSet.visible" :title="dialogSet.title" title="工位人员配置" width="500" @closed="cancelSet">
      <el-form ref="formSetRef" :model="formSet" :rules="rulesSet" label-width="auto">
        <el-form-item label="部门" prop="deptList">
          <el-cascader
            v-model="formSet.deptList"
            :options="departOptions"
            :props="propsBM"
            clearable
            style="width: 100%"
            @change="handleDeptChange"
          />
        </el-form-item>
        <el-form-item label="部门人员" prop="userId">
          <el-select
            v-model="formSet.userId"
            :loading="setLoading"
            :remote-method="handleSetPerson"
            clearable
            filterable
            multiple
            placeholder="请选择部门人员"
            remote
          >
            <el-option v-for="item in personnolOptions" :key="item.userId" :label="item.userName" :value="item.userId">
              {{ item.userName }}
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitFormSet">确 定</el-button>
          <el-button @click="cancelSet">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <StaffingDialog ref="staffingDialogRef" @success="getList" />
  </div>
</template>

<script lang="ts" name="Workstation" setup>
import StaffingDialog from './components/StaffingDialog.vue';
import { addWorkstation, delWorkstation, getWorkstation, listWorkstation, updateWorkstation } from '@/api/painting/workstation';
import { deptTreeSelect, listUser } from '@/api/system/user';
import { WorkstationForm, WorkstationQuery, WorkstationVO } from '@/api/painting/workstation/types';
import { log } from 'console';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const staffingDialogRef = ref<InstanceType<typeof StaffingDialog>>();
const workstationList = ref<WorkstationVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const queryFormRef = ref<ElFormInstance>();
const workstationFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

// 状态常量定义
const STATUS = {
  DISABLED: 0,
  ENABLED: 1
} as const;

const STATUS_MAP = {
  [STATUS.DISABLED]: {
    label: '禁用',
    type: 'danger'
  },
  [STATUS.ENABLED]: {
    label: '启用',
    type: 'success'
  }
} as const;

const initFormData: WorkstationForm = {
  id: undefined,
  status: STATUS.DISABLED, // 设置默认状态为禁用
  description: undefined,
  sort: undefined,
  isDeleted: undefined,
  workCenterCode: undefined,
  workstationCode: undefined,
  workstationName: undefined,
  workstationType: undefined
};
const data = reactive<PageData<WorkstationForm, WorkstationQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    status: undefined,
    description: undefined,
    sort: undefined,
    isDeleted: undefined,
    workCenterCode: undefined,
    workstationCode: undefined,
    workstationName: undefined,
    workstationType: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '主键ID不能为空', trigger: 'blur' }],
    status: [{ required: true, message: '状态不能为空', trigger: 'change' }],
    isDeleted: [{ required: true, message: '是否删除：0-未删除，1-已删除不能为空', trigger: 'blur' }],
    workCenterCode: [{ required: true, message: '所属工作中心编码不能为空', trigger: 'blur' }],
    workstationCode: [{ required: true, message: '工位编码不能为空', trigger: 'blur' }],
    workstationName: [{ required: true, message: '工位名称不能为空', trigger: 'blur' }],
    workstationType: [{ required: true, message: '工位类型不能为空', trigger: 'change' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询工位管理列表 */
const getList = async () => {
  loading.value = true;
  const res = await listWorkstation(queryParams.value);
  workstationList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  workstationFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: WorkstationVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加工位管理';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: WorkstationVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getWorkstation(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改工位管理';
};

/** 提交按钮 */
const submitForm = () => {
  workstationFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateWorkstation(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addWorkstation(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: WorkstationVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除工位管理编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delWorkstation(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'painting/workstation/export',
    {
      ...queryParams.value
    },
    `workstation_${new Date().getTime()}.xlsx`
  );
};

/** 修改状态 */
const handleStatusChange = async (row: WorkstationVO) => {
  const newStatus = row.status === STATUS.ENABLED ? STATUS.DISABLED : STATUS.ENABLED;
  const text = STATUS_MAP[newStatus].label;
  try {
    await proxy?.$modal.confirm(`确认要${text}"${row.workstationName}"吗？`);
    await updateWorkstation({
      ...row,
      status: newStatus
    });
    proxy?.$modal.msgSuccess(`${text}成功`);
    await getList();
  } catch (error) {
    console.error(error);
  }
};

//设置工位人员
const dialogSet = reactive<DialogOption>({
  visible: false,
  title: '设置工位管理'
});
const propsBM = {
  checkStrictly: true
};
const formSet = reactive({
  userId: [] as string[], // 部门人员
  deptId: undefined,
  deptList: [] as number[]
});
const formSetRef = ref<ElFormInstance>();
const rulesSet = reactive({
  userId: [{ required: true, message: '请选择部门人员', trigger: 'change' }],
  deptList: [{ required: true, message: '请选择部门', trigger: 'change' }]
});
const setLoading = ref(false);
//部门树
const departOptions = ref([]);
//部门人员
const personnolOptions = ref<Array<{ userId: string | number; userName: string }>>([]);
//部门树选择
const handleDeptChange = async (val: any) => {
  console.log(val, '部门树选择');
  const deptId = val[val.length - 1]; // 获取最后一个选中的部门ID
  formSet.deptId = deptId; // 设置部门ID
  // 清空人员选择
  formSet.userId = undefined; // 清空人员选择
  // 调用人员搜索
  const res = await listUser({
    deptId: deptId,
    pageSize: 10,
    pageNum: 1
  });
  // 设置人员选项
  personnolOptions.value = res.rows.map((item) => ({
    userId: item.userId,
    userName: item.userName
  }));
};
//部门人员搜索
const handleSetPerson = async (query: string) => {
  setLoading.value = true;
  try {
    const params = {
      deptId: formSet.deptId,
      userName: query,
      pageSize: 10,
      pageNum: 1
    };
    const res = await listUser(params);
    personnolOptions.value = res.rows.map((item) => ({
      userId: item.userId,
      userName: item.userName
    }));
  } catch (error) {
    console.error('获取部门人员失败', error);
  } finally {
    setLoading.value = false;
  }
};

const handleSetting = (row?: WorkstationVO) => {
  dialogSet.visible = true;
};
const getdeptTreeSelect = async () => {
  try {
    const res = await deptTreeSelect();
    departOptions.value = convertTreeData(res.data);
    // 如果需要设置默认选中部门，可以在这里设置
    formSet.deptId = [100]; // 部门ID
  } catch (error) {
    console.error('获取部门树形选择数据失败', error);
  }
};
getdeptTreeSelect();
// 将原始树形数据转换为所需格式
function convertTreeData(originalData: any[]): any[] {
  return originalData.map((item) => {
    const { id, label, children } = item;
    const newItem: any = { value: id, label };
    if (children && children.length > 0) {
      newItem.children = convertTreeData(children);
    }
    return newItem;
  });
}

/** 提交设置 */
const submitFormSet = () => {
  formSetRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      // console.log(formSet, '提交设置的表单数据');
      // buttonLoading.value = true;
      // try {
      //   // 这里可以调用设置工位人员的API
      //   // await setWorkstationPerson(formSet);
      //   proxy?.$modal.msgSuccess('设置成功');
      //   dialogSet.visible = false;
      //   await getList();
      // } catch (error) {
      //   console.error('设置工位人员失败', error);
      // } finally {
      //   buttonLoading.value = false;
      // }
    }
  });
};
/** 取消设置 */
const cancelSet = () => {
  dialogSet.visible = false;
  formSet.userId = []; // 清空人员选择
  formSet.deptList = []; // 清空部门选择
  formSetRef.value?.resetFields(); // 重置表单
};

onMounted(() => {
  getList();
});

const handleStaffing = (row: WorkstationVO) => {
  staffingDialogRef.value?.show(row);
};
</script>
